package com.alex;

import static com.anythink.core.api.ATInitMediation.getStringFromMap;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.splashad.unitgroup.api.CustomSplashAdapter;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.CSJSplashCloseType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;

import java.util.Map;

public class AlexGromoreSplashAdapter extends CustomSplashAdapter {

    boolean isC2SBidding = false;
    String slotId;
    AlexGromoreConfig mATConfig;
    private Map<String, Object> mNetworkMap;
    CSJSplashAd mCSJSplashAd;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra,
                                    Map<String, Object> localExtra) {
        if (!(context instanceof Activity)) {
            notifyATLoadFail("", "Gromore: context must be activity");
            return;
        }
        if (!initAndVerifyRequestParams(context, serverExtra, localExtra)) {
            notifyATLoadFail("", "app_id or slot_id is empty!");
            return;
        }
        AlexGromoreInitManager.getInstance()
                .initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        //start load splash
                        //localExtra传入MediationSplashRequestInfo，配置兜底开屏相关配置
                        MediationAdSlot.Builder mediationAdSoltBuilder = new MediationAdSlot.Builder();
                        if (mATConfig.splashRequestInfo != null) {
                            mediationAdSoltBuilder.setMediationSplashRequestInfo(
                                    mATConfig.splashRequestInfo);
                        }
                        AdSlot adSlot = new AdSlot.Builder().setCodeId(slotId)
                                .setImageAcceptedSize(mATConfig.mWidth, mATConfig.mHeight)
                                .setMediationAdSlot(mediationAdSoltBuilder.build()).build();

                        TTAdNative adNativeLoader = TTAdSdk.getAdManager()
                                .createAdNative((Activity) context);//必须传入Activity才会有加载回调
                        adNativeLoader.loadSplashAd(adSlot, new TTAdNative.CSJSplashAdListener() {
                            @Override
                            public void onSplashLoadSuccess() {
                            }

                            @Override
                            public void onSplashLoadFail(CSJAdError csjAdError) {
                                notifyATLoadFail(csjAdError.getCode() + "", csjAdError.getMsg());
                            }

                            @Override
                            public void onSplashRenderSuccess(CSJSplashAd csjSplashAd) {
                                mCSJSplashAd = csjSplashAd;
                                if (isC2SBidding) {
                                    runOnNetworkRequestThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                if (mBiddingListener != null) {
                                                    double price = 0;
                                                    try {
                                                        price = Double.parseDouble(
                                                                mCSJSplashAd.getMediationManager()
                                                                        .getBestEcpm()
                                                                        .getEcpm());//return cent
                                                        price = price / 100;//cast to yuan
                                                    } catch (Throwable t) {

                                                    }
                                                    if (price <= 0) {
                                                        price = AlexGromoreUtil.getBestPriceInCacheNew(
                                                                mCSJSplashAd);
                                                    }

                                                    mBiddingListener.onC2SBiddingResultWithCache(
                                                            ATBiddingResult.success(price,
                                                                    System.currentTimeMillis() + "",
                                                                    null, mATConfig.mCurrency),
                                                            null);
                                                }
                                            } catch (Throwable e) {

                                            }
                                        }
                                    });
                                } else {
                                    if (mLoadListener != null) {
                                        mLoadListener.onAdCacheLoaded();
                                    }
                                }
                            }

                            @Override
                            public void onSplashRenderFail(CSJSplashAd csjSplashAd,
                                                           CSJAdError csjAdError) {
                                notifyATLoadFail(csjAdError.getCode() + "", csjAdError.getMsg());
                            }
                        }, mFetchAdTimeout);
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        notifyATLoadFail("", errorMsg);
                    }
                });

    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra,
                                       Map<String, Object> localExtra,
                                       ATBiddingListener biddingListener) {
        isC2SBidding = true;
        loadCustomNetworkAd(context, serverExtra, localExtra);
        return true;
    }


    private boolean initAndVerifyRequestParams(Context context, Map<String, Object> serverExtra,
                                               Map<String, Object> localExtra) {
        String appId = getStringFromMap(serverExtra, "app_id");
        slotId = getStringFromMap(serverExtra, "slot_id");

        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(slotId)) {
            return false;
        }

        mATConfig = new AlexGromoreConfig(context, serverExtra);
        mATConfig.parseSplashDefaultData(localExtra);

        return true;
    }

    @Override
    public void destory() {
        if (mCSJSplashAd != null && mCSJSplashAd.getMediationManager() != null) {
            mCSJSplashAd.getMediationManager().destroy();
        }
    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return AlexGromoreInitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return AlexGromoreInitManager.getInstance().getNetworkName();
    }

    @Override
    public boolean isAdReady() {
        return mCSJSplashAd != null && mCSJSplashAd.getMediationManager().isReady();
    }

    @Override
    public void show(Activity activity, ViewGroup container) {
        if (isAdReady()) {
            mCSJSplashAd.setSplashAdListener(new CSJSplashAd.SplashAdListener() {
                @Override
                public void onSplashAdShow(CSJSplashAd csjSplashAd) {
                    mNetworkMap = AlexGromoreConst.getNetworkMap(csjSplashAd);
                    if (mImpressionListener != null) {
                        mImpressionListener.onSplashAdShow();
                    }
                }

                @Override
                public void onSplashAdClick(CSJSplashAd csjSplashAd) {
                    if (mImpressionListener != null) {
                        mImpressionListener.onSplashAdClicked();
                    }
                }

                @Override
                public void onSplashAdClose(CSJSplashAd csjSplashAd, int closeType) {
                    switch (closeType) {
                        case CSJSplashCloseType.CLICK_SKIP:
                            mDismissType = ATAdConst.DISMISS_TYPE.SKIP;
                            break;
                        case CSJSplashCloseType.CLICK_JUMP:
                            mDismissType = ATAdConst.DISMISS_TYPE.CLICKAD;
                            break;
                        case CSJSplashCloseType.COUNT_DOWN_OVER:
                            mDismissType = ATAdConst.DISMISS_TYPE.TIMEOVER;
                    }


                    if (mImpressionListener != null) {
                        mImpressionListener.onSplashAdDismiss();
                    }

                }
            });
            View splashView = mCSJSplashAd.getSplashView();
            if (splashView != null) {
                ViewParent vp = splashView.getParent();
                if (vp instanceof ViewGroup) {
                    ((ViewGroup) vp).removeView(splashView);
                }
            }
            container.addView(splashView);
        }
    }

    @Override
    public Map<String, Object> getNetworkInfoMap() {
        return mNetworkMap;
    }
}
